import { Component } from '@angular/core';
import { NavController, NavParams,LoadingController , Loading} from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { DataService } from '../../services/data';
// import { AppGlobal } from '../../app/app.global';

/**
 * Generated class for the GameRuntimePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-game-runtime',
  templateUrl: 'game-runtime.html',
  providers: [DataService]
})
export class GameRuntimePage {

    public game:any
    public height:string = window.innerHeight + 'px';
    public width:string = window.innerWidth + 'px';
    public transform:string = 'rotate(-90deg) translateX(-' + window.innerHeight + 'px)';
    private loader:Loading

  constructor(public loadingCtrl: LoadingController, public navCtrl: NavController, public navParams: NavParams, public storage:Storage, public dataService: DataService) {
    this.game = this.navParams.get('game')
    this.loader = this.loadingCtrl.create({
        content: "Loading...",
      });
    this.loader.present();
    console.log(this.game)
  }

  ionViewDidEnter() {
    this.hiddenTabbar()
  }

  ionViewDidLoad() {
    this.hiddenTabbar()
    console.log('ionViewDidLoad GameRuntimePage');
    this.clearLib();

    this.dataService.getGameRecords(this.game.id).subscribe( (records) =>{
        console.log('records', records)
        for(let item of records){
            window.localStorage.setItem(item.name, item.data);
        }
        this.loadGameLib();
    })
  }

  clearLib(){
    // 初始清除lib、存档
    window.localStorage.removeItem('baye//data/dat.lib'); 
    for(let i = 0; i < 6; i++){
        window.localStorage.removeItem('baye//data//sango' + i + '.sav');
    }

    // 清楚伏魔记存档
    for(let i = 0; i < 3; i++){
        window.localStorage.removeItem('sav/fmjsave' + i);
    }
  }

  hiddenTabbar(){
    //隐藏tabbar
    let elements = document.querySelectorAll(".tabbar");
    if(elements != null) {
      Object.keys(elements).map((key) => {
          elements[key].style.display ='none';
      });
    }
  }

  loadGameLib(){
    let ithis = this;
    window['CurrGameId'] = this.game.id;
    let cacheKey = 'game/dat.lib/' + this.game.id + '/' + this.game.version;

    if(!this.game.lib){ // 三国霸业原版
        this.run("");
        return
    }
    console.log('load lib', this.game.lib)
    this.storage.get(cacheKey).then((data) => {
        if(data){
            this.run(data);
        }else{
            this.dataService.getGameLib(this.game.lib).subscribe( (blob) =>{
                var reader = new FileReader();
                if (!reader) {
                    console.log("浏览器不支持载入文件");
                    return
                }
                reader.onload = function() {
                    let binLib = reader.result;
                    if(ithis.game.category_id == 1){
                        if (binLib.length == 622874) {
                            binLib = binLib.slice(425984);
                        }
                    }
                    var hexLib = ithis.arr2hex(binLib);
                    ithis.storage.set(cacheKey, hexLib)
                    console.log('set storage', cacheKey)
                    ithis.run(hexLib);
                }
                reader.readAsBinaryString(blob);
            });
        }
    })
  }

  run(hexLib){
    if(this.game.category_id == 1){ // 三国
        this.runBaye(hexLib);
    }else{
        this.runRPG(hexLib);
    }
  }

  runRPG(hexLib){
    this.loadScripts([
        "assets/libs/error-handle.js",
        "assets/libs/rpg/jquery.min.js",
        "assets/libs/rpg/encoding-indexes.js",
        "assets/libs/rpg/encoding.js",
        "assets/libs/rpg/sys.js",
        "assets/libs/rpg/kotlin.js",
        "assets/libs/rpg/keyboard.js",
        "assets/libs/rpg/font.js",
        "assets/libs/rpg/nipplejs.min.js",
        "assets/libs/rpg/jquery.mobile-events.js"
      ], ()=>{
        window['fmj']['rom']["DAT.LIB"] = hexLib
        this.loadScripts([
            "assets/libs/rpg/fmj.core.js",
            "assets/libs/rpg/start.js"
        ], () => {
            this.loader.dismiss();
        });
    });
  }

  runBaye(hexLib) {
    // window.localStorage.setItem('baye//data/dat.lib', hexLib);
    window['dynLib'] = hexLib
    console.log('hexLib.length', hexLib.length)
    let slg = this.game.engine_version == '2' ? "slg2" : "slg";
    this.loadScripts([
      "assets/libs/error-handle.js",
      "assets/libs/" + slg + "/jquery.min.js",
      "assets/libs/" + slg + "/encoding-indexes.js",
      "assets/libs/" + slg + "/encoding.js",
      "assets/libs/" + slg + "/sprintf.js",
      "assets/libs/" + slg + "/lcd.js",
      "assets/libs/" + slg + "/baye.js",
      "assets/libs/" + slg + "/bridge.js",
      
      "assets/libs/" + slg + "/start.js",
    ], () => {
        this.loader.dismiss();
    })
  }

  loadScripts(array,callback){
    var loader = function(src,handler){
        var script = document.createElement("script");
        script.src = src;
        script.onload = script.onactivate = function(){
            script.onactivate = script.onload = null;
            handler();
        }
        // var head = document.getElementsByTagName("head")[0];
        document.body.appendChild( script );
    };
    (function run(){
        if(array.length!=0){
            loader(array.shift(), run);
        }else{
            callback && callback();
        }
    })();
    }


    arr2hex = function(s){
        var i, l, o = "", n;
        s += "";
        for (i = 0, l = s.length; i < l; i++) {
            n = s.charCodeAt(i).toString(16)
            o += n.length < 2 ? "0" + n : n;
        }
        return o;
    }

        //当退出页面的时候
    ionViewWillLeave() {
        let elements = document.querySelectorAll(".tabbar");
        if(elements != null) {
            Object.keys(elements).map((key) => {
                elements[key].style.display ='flex';
            });
        }
    }  

    goBack(){
        window.location.href = '/index.html'
    }

}
